/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.gw.android;

import java.io.InputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.io.IOUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ApplicationConfigurationParser {
	public void parse(InputStream source) throws Exception {
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			ApplicationHandler handler = new ApplicationHandler();
			parser.parse(source, handler);
		} catch (SAXException e) {
			if (e instanceof BreakParseException) return;
			else throw e;
		}
	}
	
	public void parse(String source) throws Exception {
		parse(IOUtils.toInputStream(source));
	}
	
	private String displayName = null;
	private String textColor = null;
	private String backgroundColor = null;
	private String logoImage = null;
	private String loginUrl = null;
	private String repository = null;
	private boolean validXml = false;
	
	public String getDisplayName() {
		return displayName;
	}
	
	public String getTextColor() {
		return textColor;
	}
	
	public String getBackgroundColor() {
		return backgroundColor;
	}

	public String getLogoImage() {
		return logoImage;
	}
	
	public String getLoginUrl() {
		return loginUrl;
	}

	public String getRepository() {
		return repository;
	}
	
	public boolean isValid(){
		return validXml;
	}

	@SuppressWarnings("serial")
	private class BreakParseException extends SAXException { }
	
	private class ApplicationHandler extends DefaultHandler {
		private static final String APPLICATION = "Application";
		
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			if (localName.equalsIgnoreCase(APPLICATION)) {
				displayName = attributes.getValue("displayName");
				textColor = attributes.getValue("textColor");
				backgroundColor = attributes.getValue("backgroundColor");
				logoImage = attributes.getValue("logoImage");
				loginUrl = attributes.getValue("loginUrl");
				repository = attributes.getValue("repository");
				validXml = true;
				throw new BreakParseException();
			}
		}
	}
}
